import { ref, onMounted } from 'vue';

// 初始化SEO数据
interface SeoDataType {
  title: string;
  description: string;
  keywords: string;
  url: string;
  image: string;
}

interface PageDataType {
  title?: string;
  description?: string;
  keywords?: string;
  url?: string;
  icon?: string;
  classify?: Array<{
    id: string;
    name: string;
    url: string;
  }>;
  homeConfig?: {
    featured_products?: Array<{
      name: string;
      url: string;
      images?: string[];
      price: number;
    }>;
  };
}

interface JsonLdType {
  "@context": string;
  "@type": string;
  name: string;
  description: string;
  url: string;
  image: string;
  publisher: {
    "@type": string;
    name: string;
    logo: {
      "@type": string;
      url: string;
    };
  };
  mainEntity?: any;
  significantLink?: any;
}
// Page 数据
const pageData = ref<PageDataType | null>(null);
export function useSeo() {
  // SEO 数据
  const seoData = ref<SeoDataType>({
    title: 'Lannuan Clothing - Premium Fashion Online Store',
    description: 'Shop the latest fashion trends at Lannuan. Discover premium quality clothes, shoes, accessories and more.',
    keywords: 'clothing, fashion, online shopping, accessories, premium quality',
    url: 'https://lannuan.com/home/index.html',
    image: ''
  });


  // 更新Meta标签
  const updateMetaTag = (name: string, content: string) => {
    let metaTag = document.querySelector(`meta[name="${name}"]`);
    if (!metaTag) {
      metaTag = document.createElement('meta');
      metaTag.setAttribute('name', name);
      document.head.appendChild(metaTag);
    }
    metaTag.setAttribute('content', content);
  };

  // 设置Open Graph标签
  const setOpenGraphTags = () => {
    const ogTags = {
      'og:title': seoData.value.title,
      'og:description': seoData.value.description,
      'og:type': 'website',
      'og:url': seoData.value.url,
      'og:image': seoData.value.image
    };

    // 添加Open Graph标签
    Object.entries(ogTags).forEach(([property, content]) => {
      if (!content) return; // 跳过空值

      let metaTag = document.querySelector(`meta[property="${property}"]`) || document.createElement('meta');
      metaTag.setAttribute('property', property);
      metaTag.setAttribute('content', content as string);
      document.head.appendChild(metaTag);
    });
  };

  // 添加JSON-LD结构化数据
  const addJsonLdStructuredData = () => {
    if (!pageData.value) return;

    // 创建JSON-LD结构化数据
    const jsonLd: JsonLdType = {
      "@context": "https://schema.org/",
      "@type": "WebPage",
      "name": seoData.value.title,
      "description": seoData.value.description,
      "url": seoData.value.url,
      "image": seoData.value.image,
      "publisher": {
        "@type": "Organization",
        "name": "LANNUAN Clothing",
        "logo": {
          "@type": "ImageObject",
          "url": "https://melov-net.oss-us-west-1.aliyuncs.com/lannuan/logo_lannuan.ico"
        }
      }
    };

    // 添加分类数据
    if (pageData.value.classify && Array.isArray(pageData.value.classify)) {
      jsonLd.mainEntity = {
        "@type": "ItemList",
        "itemListElement": pageData.value.classify.map((item, index) => ({
          "@type": "ListItem",
          "position": index + 1,
          "name": item.name,
          "url": `https://lannuan.com/classify/${item.url}-${item.id}.html`
        }))
      };
    }

    // 添加推荐产品
    if (pageData.value.homeConfig?.featured_products && pageData.value.homeConfig.featured_products.length > 0) {
      jsonLd.significantLink = pageData.value.homeConfig.featured_products.map(product => ({
        "@type": "Product",
        "name": product.name,
        "url": `https://lannuan.com/product/${product.url}.html`,
        "image": product.images?.[0],
        "offers": {
          "@type": "Offer",
          "price": product.price,
          "priceCurrency": "USD"
        }
      }));
    }

    // 移除现有的JSON-LD脚本
    const existingScript = document.querySelector('script[type="application/ld+json"]');
    if (existingScript) {
      existingScript.remove();
    }

    // 添加新的JSON-LD脚本
    const jsonLdScript = document.createElement('script');
    jsonLdScript.type = 'application/ld+json';
    jsonLdScript.textContent = JSON.stringify(jsonLd);
    document.head.appendChild(jsonLdScript);
  };

  // 初始化SEO数据
  const initSeo = async (dataUrl: string = '/') => {
    try {
      // 加载静态数据
      const response = await fetch(dataUrl);
      if (response.ok) {
        const data = await response.json();
        pageData.value = data;

        // 更新SEO数据
        if (data) {
          seoData.value = {
            title: data.title || seoData.value.title,
            description: data.description || seoData.value.description,
            keywords: data.keywords || seoData.value.keywords,
            url: `https://lannuan.com/`,
            image: data.icon || ''
          };

          // 设置页面标题
          document.title = seoData.value.title;

          // 设置描述标签
          updateMetaTag('description', seoData.value.description);

          // 设置关键词标签
          updateMetaTag('keywords', seoData.value.keywords);

          // 设置规范链接标签
          const canonicalLink = document.querySelector('link[rel="canonical"]') || document.createElement('link');
          canonicalLink.setAttribute('rel', 'canonical');
          canonicalLink.setAttribute('href', seoData.value.url);
          document.head.appendChild(canonicalLink);

          // 设置Open Graph标签
          setOpenGraphTags();

          // 添加JSON-LD结构化数据
          addJsonLdStructuredData();
        }
      }
    } catch (error) {
      console.error('Failed to load SEO data:', error);
    }
  };

  return {
    seoData,
    pageData,
    initSeo
  };
}
